"""
WSGI Middleware to create a APP client for blogging.
"""
import re, os, amara, dateutil, urlparse, posixpath, urllib
from mimetypes import guess_type
import httplib2

from pprint import pprint

# from selector import *
from wsgiappclient.wsgidispatcher import Dispatcher
from paste.request import parse_formvars, get_cookies
from paste.httpexceptions import *
from beaker.middleware import SessionMiddleware

from wsgiappclient.namespaces import *
from wsgiappclient.utils import get_base_url, setup_xslt_params
from wsgiappclient.atompubclient import AtomPubClient
from wsgiappclient.clientatomentry import ClientAtomEntry
from wsgiappclient.openidauth import OpenIDRequestMiddleware
from wsgiappclient.controllers.user import UserController
from wsgiappclient.controllers.collection import CollectionController
# from wsgiappclient.store.s3store import S3UserStore

from pkg_resources import resource_string

class WsgiAtomPubClientMiddleware(object):

    def __init__(self, app_conf, app=None):
        if not app_conf.get('base_url'):
            print "base_url must be provided in the configuration."
            import sys
            sys.exit(1)
        self.user_id = app_conf.get('test_openid', None)
        self.app_conf = app_conf
        self.app_conf['trusted_root'] = self.app_conf['base_url']
        self.auth = OpenIDRequestMiddleware(self.app_conf)
        self.user = UserController(self.auth, self.app_conf)
        self.collection = CollectionController(self.auth, self.app_conf)
        self._d = Dispatcher()
        self._d.add('/static/{static_file:any}', self.static)
        self._d.add(
            '/blog/{collection_id}/{action}[/{id}][/]',
            self.collection
        )
        self._d.add(
            '/[{model}[/{id}[/{action}[/{target}]]]][/]',
            self.user
        )

    def __call__(self, environ, start_response):
        # print "in middleware call"
        #testing
        # set openid cookie
        environ['xsltemplate.params'] = {
            'base_url' : self.app_conf['base_url'],
        }
        is_static = environ['PATH_INFO'].startswith('/static')
        is_openid = environ['PATH_INFO'].startswith('/openid')
        if not is_static and not is_openid:
            sess = get_session(environ)
            if not sess.get('user_id'):
                return self.auth(environ, start_response)
        return self.do_dispatch(environ, start_response)

    def do_dispatch(self, environ, start_response):
        return self._d(environ, start_response)

    def static(self, environ, start_response):
        fn = environ['wsgiorg.routing_args'][1]['static_file']
        # from pprint import pprint
        # pprint(environ)
        fn = posixpath.join('xslt/static', fn)
        #print "Trying to get: %s" % fn
        try:
            # fn = file(self.sf.fget(fn), 'rb').read()
            ctype = guess_type(fn)[0]
            fn = resource_string(__name__, fn)
            if not ctype:
                ctype = "text/xml"
            start_response('200 OK', [('content-type', ctype)])
            return [fn]
        except IOError, e:
            start_response('404 Not Found', [('content-type', 'text/plain')])
            error = '"%s" not found\n\n%s' % (fn, e)
            return [error,]

    def post_index(self, environ, start_response):
        #print "in add_service"
        post = parse_formvars(environ)
        sess = get_session(environ)
        if post.get('action'):
            action = post['action']
            print "Have action: %s" % action
            if action == 'user-add-collections':
                user = User(sess['user_id'])
                collection_uris = post.getall('collection_urls')
                for c in collection_uris:
                    username = post.get('username', None)
                    password = post.get('password', None)
                    if c:
                        user.add_collection(c, username, password)
                        user.save()
            if post['action'] == 'service-get-collections':
                data = {
                    'service' : post['app_service'],
                    'username' : post['username'],
                    'password' : post['password'],
                    'xml_base' : post['app_service']
                }
                environ['wsgiappclient.post_index_data'] = data
                save_session(environ)
            return self.get_index(environ, start_response)
        return self.get_index(environ, start_response)

def get_session(environ):
    return environ['beaker.session']

def save_session(environ):
    environ['beaker.session'].save()


"""
This function defines the WSGI entry point for this application.
"""
from xsltemplates import TemplateMiddleware

def make_app(global_conf, **app_conf):
    app = WsgiAtomPubClientMiddleware(app_conf)
    app = SessionMiddleware(app, key="wsigappclient.session", secret="ionrocks")
    app = TemplateMiddleware(app_conf, app)
    return app

